package cn.jjxx.modules.sys.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.SpringContextHolder;
import cn.jjxx.core.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializeFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import cn.jjxx.modules.sys.entity.Organization;
import cn.jjxx.modules.sys.entity.Report;
import cn.jjxx.modules.sys.entity.ReportOrg;
import cn.jjxx.modules.sys.service.IOrganizationService;
import cn.jjxx.modules.sys.service.IReportService;
import cn.jjxx.modules.sys.utils.UserUtils;

/**   
 * @Title: 报表管理
 * @Description: 报表管理
 * @author zcg
 * @date 2018-05-23 08:19:38
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/sys/report")
public class ReportManageController extends BaseBeanController<Report> {
	
	private static final String REPORT_UPLOAD_BASE = "report/";//报表上传基础路径

    @Autowired
    protected IReportService reportService;
    @Autowired
    protected IOrganizationService organizationService;

	/**
	 * @Description: 根据获取报表管理的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    public Report get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return reportService.selectById(id);
        } else {
            return newModel();
        }
    }

	/**
	 * @Description: 跳转至报表管理的列表界面 .<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }
    
    /**
     * @Description: 跳转至绑定组织 .<br>
     * @param reportId 报表Id .<br>
     * @author 郑成功 .<br>
     * @date 2018-8-6 下午10:07:07.<br>
     */
    @RequestMapping(value="bindOrg",method = RequestMethod.GET)
    public String bindOrg(Model model, HttpServletRequest request, HttpServletResponse response,String reportId) {
    	//获取已经勾选的组织
    	List<ReportOrg> selects = reportService.findOrgReport(reportId);
    	List<String> orgIds = UserUtils.getOrgChilds(true, true);
    	List<Organization> orgs = organizationService.selectBatchIds(orgIds);
    	request.setAttribute("orgs", JSONArray.toJSON(orgs));
    	request.setAttribute("selects", JSONArray.toJSON(selects));
        return display("bindOrg");
    }

	/**
	 * @Description: 报表管理的列表界面获取列表结果 .<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    @PageableDefaults(sort = "id=desc")
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<Report> entityWrapper = new EntityWrapper<Report>(entityClass);
        entityWrapper.setTableAlias("t.");
        entityWrapper.eq("1", 1);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Report> pagejson = new PageJson<Report>(reportService.list(queryable,entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

	/**
	 * @Description: 跳转至报表管理的添加界面 .<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }
    
	/**
	 * @Description: 新增报表管理的数据 .<br>
	 * @param report 报表管理实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") Report report, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(report, request, response, result);
    }
	/**
	 * @Description: 跳转至报表管理的更新界面 .<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        Report report = get(id);
        model.addAttribute("data", report);
        return display("edit");
    }

	/**
	 * @Description: 修改报表管理的数据 .<br>
	 * @param report 报表管理实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") Report report, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(report, request, response, result);
    }
	/**
	 * @Description: 执行保存报表管理的数据操作 .<br>
	 * @param report 报表管理实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(Report report, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(report, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(report.getId())) {
                reportService.insert(report);
            } else {
                reportService.insertOrUpdate(report);
            }
            ajaxJson.setData(report);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

	/**
	 * @Description: 单条删除报表管理 .<br>
	 * @param id 单据Id.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            reportService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 执行保存报表管理的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            reportService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 跳转至报表管理的查看界面 .<br>
	 * @param ids 单据Id.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        Report report = get(id);
        model.addAttribute("data", report);
        return display("edit");
    }

	/**
	 * @Description: 验证报表管理功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-05-23 08:19:38.<br>
	 */
    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<Report> entityWrapper = new EntityWrapper<Report>(entityClass);
            valid = reportService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }
    
    /**
     * @Description: 报表上传 .<br>
     * @param request
     * @param response
     * @param billId 单据Id .<br>
     * @author 郑成功 .<br>
     * @date 2018-6-19 下午4:59:23.<br>
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
    public AjaxJson upload(HttpServletRequest request, HttpServletResponse response,String billId){
    	Report report = get(billId);
    	String uploadPath = REPORT_UPLOAD_BASE+report.getModule();
    	return SpringContextHolder.getBean(AttachmentController.class).specifyUpload(request, response, uploadPath);
    }
    
    /**
     * @Description: 绑定报表组织 .<br>
     * @param request http请求.<br>
     * @param id 报表Id.<br>
     * @author 郑成功 .<br>
     * @date 2018-6-19 下午3:18:37.<br>
     */
    @RequestMapping(value = "saveBindOrg", method=RequestMethod.POST)
    @ResponseBody
    public AjaxJson bindOrg(HttpServletRequest request,String reportId,String[] orgIds){
    	AjaxJson ajaxJson = new AjaxJson();
    	boolean flag = reportService.bindOrg(reportId,orgIds);
    	if(flag){
    		ajaxJson.setMsg("绑定成功");
    	}else{
    		ajaxJson.setMsg("绑定失败");
    		ajaxJson.setRet(AjaxJson.RET_FAIL);
    	}
    	return ajaxJson;
    }
}
